package tgc.edu.szxt.demo.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import tgc.edu.szxt.demo.service.SysUserService;

@Configuration //配置文件
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
	@Autowired
	private SysUserService sysUserService;
	
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(sysUserService).passwordEncoder(new BCryptPasswordEncoder());//BCryptPasswordEncoder 加密方法 找到合法用戶 用戶密碼
		auth.inMemoryAuthentication().withUser("SZXT").password("{noop}123456").roles("DIY","ADMIN");
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.csrf().disable();
		http.headers().frameOptions().disable();    //解决iframe与安全器兼容性问题
		http.formLogin()
			.loginPage("/login")//登录界面
			.permitAll()//显示全部
			.usernameParameter("username")
			.passwordParameter("pwd")
			.successForwardUrl("/main2")//成功
			.failureUrl("/login?error");//错误
		http.logout().logoutUrl("/logout").permitAll();
		http.authorizeRequests().antMatchers("/static/**","/webjars/**").permitAll();
		http.authorizeRequests().anyRequest().authenticated();    //除此之外的都必须通过请求验证才能访问
		
	}

//	public static void main(String[] args) {
//		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
//		String encode = encoder.encode("1111");
//		System.out.println(encode);
//	}

}
